<template>
<div class="layout-app" ref='myBox'>
	<!-- main -->
<el-dialog :title="diglogTile" :visible.sync="exaDialogVisible" width="58%" :before-close="handleClose" :destroy-on-close='true' :modal="false">
		<!-- 新增 -->
	<div class="addAcc">
			<!-- tabs -->
			<div class="tabs">
				<div class="tabsMain">
					<!-- 表单 -->
					<el-form ref="form" :model="addForm" label-width="80px" size="mini" :disabled="true">
					<el-row :gutter="20">
						  <el-col :xs="val.xs" :sm="val.xs" :md="val.md" :lg="val.lg" :xl="val.xl" type="flex" v-for="(val,i) in formType" :key="i">
							  <!-- input -->
							  <el-form-item v-if="val.type == 'input'" :label="val.label">
								<el-input :suffix-icon='val.prefix' v-model="$data.addForm[val.modelValue]" :placeholder="val.placeholder" :disabled="val.disabled" ></el-input>
							  </el-form-item>
							  <!-- select -->
							  <el-form-item v-if="val.type == 'select'" :label="val.label">
								<el-select v-model="$data.addForm[val.modelValue]" filterable placeholder="请选择" :disabled="val.disabled">
									<el-option v-for="item in $data[val.op]" :key="item.id" :label="item.label" :value="item.id"> 
									<span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
								</el-select>
							  </el-form-item>
							  <!-- date -->
							  <el-form-item v-if="val.type == 'date'" :label="val.label">
								<el-date-picker class="autoWidth" @focus="testDate(val,i)"
								type="date" placeholder="选择日期" v-model="$data.addForm[val.modelValue]" :disabled="val.disabled"></el-date-picker>
							  </el-form-item>
							  <!-- btn -->
							  <el-form-item v-if="val.type == 'btn'">
								<el-button type="primary" plain @click="clickEvents(val,i)">{{ val.label }}</el-button>
							  </el-form-item>
						  </el-col>
						</el-row>
					</el-form>
					<!-- table -->
					<div class="table">
						<el-table :data="tableData" border @row-dblclick="handledbRow" :style="{ width: tableWidth + 'px' }">
							<el-table-column
							  prop="drugCode"
							  label="药品编码"
							  width="120"
							  align="center"
							></el-table-column>
							<el-table-column
							  prop="drugName"
							  label="药品名称"
							  width="150"
							  align="center"
							></el-table-column>
							<el-table-column
							  prop="drugSpec"
							  label="药品规格"
							  width="120"
							  align="center"
							></el-table-column>
							<el-table-column
							  prop="pacSpec"
							  label="包装规格"
							  width="120"
							  align="center"
							></el-table-column>
							<el-table-column
							  prop="manuLotnum"
							  label="批号"
							  width="120"
							  align="center"
							></el-table-column>
							<el-table-column
							  prop="purcCnt"
							  label="数量"
							  width="128"
							  align="center"
							></el-table-column>
							<el-table-column prop="purcCnt" label="入库单位" width="120">
							  <template slot-scope="scope">
							    <span v-if="scope.row.purcType === '1'">{{ scope.row.dosUnt }}</span>
							    <span v-else>{{ scope.row.pacUnt }}</span>
							  </template>
							</el-table-column>
							<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
							<!-- fixed -->
							<el-table-column fixed="left" label="行号" type="index" width="68" align="center"></el-table-column>
						</el-table>
						<div class="total">
							<span>成本合计金额：</span><el-input v-model="cbValue" style="width: 128px;" size="mini" :disabled='totaldisabled'></el-input>
							<span style="margin-left: 12px;">零售合计金额：</span><el-input v-model="lsValue" style="width: 128px;" size="mini" :disabled='totaldisabled'></el-input>
						</div>
					</div>
				</div>
			</div>
			<!-- 提交 -->
			<div v-if="diglogTile === '草稿'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="primary" @click="Submit">确定提交</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 审核 -->
			<div v-if="diglogTile === '审核'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="danger" @click="refuseExamine">拒绝审核</el-button>
				<el-button size="mini" type="primary" @click="exaSubmit">确定审核</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 过单 -->
			<div v-if="diglogTile === '过单'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="danger" @click="refusePassOrder">拒绝过单</el-button>
				<el-button size="mini" type="primary" @click="passOrderSubmit">确定过单</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 冲销 -->
			<div v-if="diglogTile === '冲销'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="danger" @click="destroySubmit">冲销</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">再想想</el-button>
			<!-- 	<el-button size="mini" type="primary" @click="passOrderSubmit">确定过单</el-button> -->
			</div>
			
	</div>
</el-dialog>
</div>
</template>

<script>
// self
import AccType from './exaStoreType.js'
import addForm from './addForm.js' //Form表单
// prop

// ext
import { getLunar } from 'chinese-lunar-calendar'

// 接口
import { 
	addPurchasingPlan,
	getWare,selectDropDownList,selectInformation,
	getDrugDetails,toDrugExamine,
	} from "@/api/PSI.js";
export default {
	props: ['parentMethod'],
	inject: ['reload'], // 无痕刷新
	components:{
		
	},
	data(){
		return{
			//str
			diglogTile:'', // 动态页面的动态标题
			tableWidth:'', //右侧表格动态宽度
			totalAmt:'', //合计金额
			value:'',
			deptCode:'',
			cbValue:'',
			lsValue:'',
			getLunarDay: '',
			areaCode:'',
			areaPName:'',
			idx:'',
			//num
			
			//ble
			disabled:true,
			totaldisabled:true,
			exaDialogVisible:false,
			dialogFormVisible:false,
			//arr
			formType:[],
			tableData:[],
			selectOption:[{id:1,label:'西药库',value:'西药库'}],
			ghdwOption:[],
			nameOption:[],
			tableRows:[
				{ name:"成本单价", prop:"purcPric", type:"" },{ name:"成本金额", prop:"purcAmt", type:"" },
				{ name:"零售单价", prop:"salePric", type:"" },{ name:"零售金额", prop:"saleAmt", type:"" },
				{ name:"生产厂家", prop:"prodentpName", type:"" },{ name:"生产批号", prop:"manuLotnum", type:"" },
			],
			//obj
			addForm:{}, // form表单 * saleAmt
			options:[],
			ssrOption:[],
			gysOption:[],
		}
	},
	mounted() {
		// 获取接口参数
		this.getAddForm();
		this.getGys();
		// 定义数据来源
		this.formType = AccType.map(function(val) { return val })
		// 获取制单人 => 当前登录用户
		this.addForm.createId = JSON.parse(localStorage.getItem('userInfo')).userId;
	},
	methods:{
		// 打开model 获取采购计划数据
		async openModel(parm){
			this.diglogTile = parm.name
			console.log(parm);
			this.exaDialogVisible = true;
			let res = await getDrugDetails({id:parm.id})
			// res.data.list[0].remark = res.data.remark
			// res.data.list[0].supplierName = res.data.supplierName
			// 遍历 res.data 的所有键名
			for (let key in res.data) {
			  // 检查键名是否在对象 A 中存在
			  if (this.addForm.hasOwnProperty(key)) {
			    // 如果存在，将 B 中的值更新到 A 中
			    this.addForm[key] = res.data[key];
			  }
			}
			console.log(this.addForm,'获取合并之后的采购入库');
			// 计算总金额
			this.cbValue = res.data.costAmt;
			// 使用 reduce 方法将 saleAmt 的值相加
			this.lsValue = res.data.list.reduce((total, item) => {
			  return total + parseFloat(item.saleAmt); // 将 saleAmt 转换为数字并累加
			}, 0); // 初始值为 0
			this.addForm.id = parm.id
			this.totalAmt = res.data.totalAmt
			this.tableData = res.data.list
		},

		deleteRow(index, rows) {
		  rows.splice(index, 1);
		},
		handleSelectCost(val) {
		  this.addForm.nativePlace = val.join(',')
		},
		// 供应商下拉列表
		async getGys(){
			let rs = await selectDropDownList();
			this.gysOption = rs.data.content.map(obj => {
			  // 将 name 替换为 label，并保留其他字段
			  return { label: obj.supplierName , ...obj };
			});
		},
		// 键盘事件
		 handleKeyup(event) {
		  // 检查按键
		  if (event.key === 'Enter') {
			// 执行相应的动作
		  }
		},
		testDate(val,i){
			this.idx = val.id
		},
		handleClose(done) {
			done();
		},
		// 确定提交
		async Submit(){
			this.addForm.state = 2
			console.log(this.addForm);
			let result = await toDrugExamine(this.addForm)
			if (result.code === 200) {
				this.reload(); // 更新数据驱动 => 父组件 shopPlan
				this.$message({ type: 'success', message: result.message});
				this.exaDialogVisible = false;
			} else {
				this.$message.error(result.message)
			}
		},
		//确定审核
		async exaSubmit(){
			this.addForm.state = 4
			console.log(this.addForm);
			let result = await toDrugExamine(this.addForm)
			if (result.code === 200) {
				this.reload(); // 更新数据驱动 => 父组件 shopPlan
				this.$message({ type: 'success', message: result.message});
				this.exaDialogVisible = false;
			} else {
				this.$message.error(result.message)
			}
		},
		// 拒绝审核
		refuseExamine(){
			this.$confirm('此操作将回退该条数据状态, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '考虑一下',
			  type: 'warning'
			}).then(async() => {
				this.addForm.state = 0
				let result = await toDrugExamine(this.addForm)
				if (result.code === 200) {
					this.reload(); // 更新数据驱动 => 父组件 shopPlan
					this.$message({ type: 'success', message: result.message});
					this.exaDialogVisible = false;
				} else {
					this.$message.error(result.message)
				}
			}).catch(() => {
				this.$message({ type: 'info', message: '考虑一下'});          
			});
		},
		//确定过单
		async passOrderSubmit(){
			this.addForm.state = 5
			console.log(this.addForm,'过单数据');
			let result = await toDrugExamine(this.addForm)
			if (result.code === 200) {
				this.reload(); // 更新数据驱动 => 父组件 shopPlan
				this.$message({ type: 'success', message: result.message});
				this.exaDialogVisible = false;
			} else {
				this.$message.error(result.message)
			}
		},
		// 拒绝过单
		refusePassOrder(){
			this.$confirm('此操作将回退该条数据状态, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '考虑一下',
			  type: 'warning'
			}).then(async() => {
				this.addForm.state = 2
				console.log(this.addForm);
				let result = await toDrugExamine(this.addForm)
				if (result.code === 200) {
					this.reload(); // 更新数据驱动 => 父组件 shopPlan
					this.$message({ type: 'success', message: result.message});
					this.exaDialogVisible = false;
				} else {
					this.$message.error(result.message)
				}
			}).catch(() => {
				this.$message({ type: 'info', message: '考虑一下'});          
			});
		},
		// 草稿保存
		async draftSubmit(){
			 this.addForm.list.push(this.lists)
			 this.addForm.totalAmt = this.cbValue
			 this.addForm.state = 0
			 console.log(this.addForm);
			 let result = await addPurchasingPlan(this.addForm)
			 if (result.code === 200) {
			 	this.reload(); // 更新数据驱动 => 父组件 shopPlan
			 	this.$message({ type: 'success', message: result.message});
			 	this.exaDialogVisible = false;
			 } else {
			 	this.$message.error(result.message)
			 }
		},
		// 冲销
		async destroySubmit(){
			this.$confirm('此操作将冲销该条数据库存, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '取消',
			  type: 'warning'
			}).then(async() => {
				// 冲销
				this.addForm.state = 6
				console.log(this.addForm,'冲销数据');
				let result = await toDrugExamine(this.addForm)
				if (result.code === 200) {
					this.reload(); // 更新数据驱动 => 父组件 shopPlan
					this.$message({ type: 'success', message: result.message});
					this.exaDialogVisible = false;
				} else {
					this.$message.error(result.message)
				}
			}).catch(() => {
			  this.$message({
				type: 'info',
				message: '已取消'
			  });          
			});
		},
		//sons
		// db events
		handledbRow(row, column, event){
			if(row){ this.form = row; this.watchDialogVisible = true } else { console.log('fail'); }
			// console.log(this.form);
			this.formdisabled = true
			// this.form.textSpell = this.makePy(this.form.label).toLocaleUpperCase()
			// console.log(this.form.textSpell);
		},
		// col 里面包含了表头字段和名称，list 是表格数据
		columnWidth(col, list) {
		  let prop = col.prop,lab = col.lab;
		  let width = 40; // 设定一个最小值
		  let maxlenStr = ""; // 最长字符串
		  for (let info of list) {
			if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		  }
		  width = Math.max(width, len(lab), len(maxlenStr));
		  // 表格自带的内边距(20px) 自调
		  return width + 12; // 这里加了 12px
		  function len(str) {
			// 实际分配长度可根据需要自行调整
			let length = 12;
			for (const char of str + "") {
			  // 英文小写字符 8px
			  if ("a" <= char && char <= "z") length += 8;
			  // 英文大写字符 8px
			  else if ("A" <= char && char <= "Z") length += 8;
			  // 中文字符 28px
			  else if (char >= "\u4e00" && char <= "\u9fa5") length += 22;
			  // 其他 8px
			  else length += 12;
			}
			return length;
		  }
		},
		// 挂载或销毁前后重新赋值后端参数
		getAddForm(){
			// 左侧提交表单
			this.addForm = addForm.map(v => {return v })[0]; // Form
			this.addMainForm = this.addForm.list[0]
			console.log(this.addForm,'原始的接口参数数据');
			// 解构赋值排除 list 属性 => 弃用
			// this.addHeadrForm = addForm.map(item => { let { list, ...newItem } = item; return newItem })[0];
		},
	},
	
}
</script>

<style lang="less" scoped>
	/deep/ .el-dialog__header{
		padding: 8px;
		background-color: #007bb0;
	}
	/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
		margin-bottom: 8px;
	}
	/deep/ .el-dialog__title{
		color: #fff;
		font-size: 12px;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close{
		color: #fff;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
		background-color: brown;
	}
	/deep/ .el-dialog__body{
		padding: 12px;
	}
	/deep/ .el-divider--horizontal{
		margin: 0;
	}
	/deep/ .el-form-item__label{
		font-size: 12px;
	}
	/deep/ .el-input--mini .el-input__inner{
		height: 26px;
	}
	/deep/ .el-table{
		font-size: 12px;
	}
.layout-app{
    width: 100%;
    height: 100%;
    display: flex;
	background-color: f8f8f8;
    .addAcc{
		// self
		// 选项卡
		.tabs{
			/deep/ .el-dialog__header{
				padding: 8px;
				background-color: #007bb0;
			}
			/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
				margin-bottom: 8px;
			}
			/deep/ .el-dialog__title{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-dialog__body{
				padding: 0;
			}
			/deep/ .el-divider--horizontal{
				margin: 0;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
			.tabsMain{
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				width: 100%;
				margin-bottom: 8px;
				.a{
					flex: 1;
					display: flex;
					align-items: center;
				}
				.table{
					width: 100%;
					margin-top: 12px;
				}
				.total{
					display: flex;
					height: 48px;
					align-items: center;
					span{
						font-size: 12px;
					}
				}
			}	
		}
		.dialog-footer{
			display: flex;
			justify-content: right;
		}
	}
}
</style>